package org.yihang.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public abstract class PinyinUtil {

	/**
	 * 将汉字转化为拼音(非汉字字符保持不变)
	 * 
	 * @param str
	 * @return
	 */
	public static String getPinyin(String str) {
		try {
			HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
			format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
			format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
			format.setVCharType(HanyuPinyinVCharType.WITH_V);
			StringBuilder sb = new StringBuilder(64);
			for (int i = 0; i < str.length(); i++) {
				char ch = str.charAt(i);
				String[] array = PinyinHelper.toHanyuPinyinStringArray(ch, format);
				if (array != null && array.length > 0) {
					sb.append(array[0]);
				} else { // 非中文
					sb.append(ch);
				}

			}
			// System.out.println(sb);
			return sb.toString().replaceAll("[（）]", "_"); // solr会把非英文字符的field转为_存储至索引
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			throw new RuntimeException(e);
		}
	}

}
